<?php

/**
 * Test actions.
 *
 * @package    5
 * @subpackage Test
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class TestActions extends sfActions
{
  public function executeShow(sfWebRequest $request)
  {
    $this->test = Doctrine_Core::getTable('Test')->findOneById($request->getParameter('id'));
    $this->forward404Unless($this->test);
    $this->test->getUserId() == $this->getUser()->getId() 
      or $this->forward('sfGuardAuth', 'secure');

    $this->paper = Doctrine_Core::getTable('Paper')->find(array($this->test->getPaperId()));

    $query = Doctrine_Core::getTable('Explanation')->createQuery('e')
      ->where('e.element_id = ?', $this->test->getElementId())
      ->andWhere('e.sub_element_id = ?', $this->test->getSubElementId())
      ->andWhere('e.paper_id = ?', $this->test->getPaperId());
    $query2 = clone $query;
    $query3 = clone $query;

    $this->single = $query->andWhere('e.cost = 0')->fetchOne(); 
    $this->explanations = $query2->leftJoin('e.paymentLog l')->andWhere('e.cost > 0')->andWhere('l.id is null')->execute(); // not payed
    $this->payed = $query3->leftJoin('e.paymentLog l')->andWhere('l.id is not null')->execute();
  }

  // new and create
  public function executePaper(sfWebRequest $request)
  {
    $this->paper = Doctrine::getTable('Paper')->findOneWithQuestionsById($request->getParameter('id'));
    $this->forward404Unless($this->paper);

    if ($request->isMethod('post')) {
      $this->data = $request->getParameter('question');
      $ids = array_keys($this->data);
      $this->isValid = true;
      foreach ($this->paper->getQuestions() as $question) {
        if (!in_array($question->getId(), $ids)) {
          $this->isValid = false; break;
        }
      }
      if ($this->isValid) {
        $result = TestAnalyzer::analyze($this->data);
        $test = new Test();
        $test->setUserId($this->getUser()->getId())
          ->setPaperId($this->paper->getId())
          ->setElementId($result[0])
          ->setSubElementId($result[1])
          ->save();
        $this->redirect('@test?id='.$test->getId());
      }
      // else show template
    }
  }
}
